const db = require('../db/mysql')
// 导入生成token的包
var jwt = require('jsonwebtoken')
// 导入加密密码的模块
const bcrypt = require('bcryptjs');
// 导入全局的配置文件
const config = require('../config')
//导入验证码
const Client = require('../authCode/index')
// 登录的处理函数
exports.logUser = (req, res) => {
    // 获取前端提交的数据
    const userinfo = req.body
    console.log(userinfo);
    // 定义SQL语句
    const sql = `SELECT * FROM LOGIN WHERE phone=?`
    db.query(sql, userinfo.phone, (err, results) => {
        //执行SQL语句失败
        if (err) return res.cc(err)
        // 执行SQL语句成功,但是获取到的数据条不等于1
        if (results.length !== 1) return res.cc('登录失败')
        // 比对密码
        const compareResult = bcrypt.compareSync(userinfo.password, results[0].password)
        if (!compareResult) return res.cc("密码错误")
        // 生成Token的字符串
        const user = { ...results[0], password: "" }
        const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: config.expiresIn })
        // 调用res.send()将Token响应给客户端
        res.send({
            status: 0,
            message: '登录成功！',
            token: 'Bearer ' + tokenStr
        })
    })

}
//验证码处理函数
let code = 0
exports.authCode = (req, res) => {
    const userinfo = req.body
    code = Math.floor(Math.random() * 9000) + 1000;
    const avg = [userinfo.phone, '阿里云短信测试', 'SMS_154950909', `{"code":"${code}"}`]
    Client.default.main(avg)
    res.send({
        status: 0,
        data: code,
        message: '发送成功！'
    })
}
//注册的处理函数
exports.regUser = (req, res) => {
    const userinfo = req.body
    const inSql = `INSERT INTO login (username,phone,password) VALUES (?,?,?)`
    const quSql = `SELECT * FROM LOGIN WHERE phone=?`
    db.query(quSql, userinfo.phone, (err, results) => {
        if (err) return res.cc(err)
        if (userinfo.authcode !== code.toString()) return res.cc('注册失败,验证码错误')
        if (results.length > 0) return res.cc('注册失败,手机号已被注册')
        if (userinfo.password !== userinfo.rePassword) return res.cc('注册失败,密码不一致')
        userinfo.password = bcrypt.hashSync(userinfo.password, 10)
        db.query(inSql, [userinfo.username, userinfo.phone, userinfo.password], (err, results) => {
            if (err) return res.cc(err)
            if (results.affectedRows !== 1) return res.cc('注册失败,请稍后在试')
            res.send({
                status: 0,
                message: '注册成功！'
            })
        })

    })

}

